package com.quanxi.qxaimain.controller.v1.forVueController;

import com.alibaba.fastjson.JSONObject;
import com.quanxi.qxaimain.common.globalException.ResponseVo;
import com.quanxi.qxaimain.common.globalException.ResultCode;
import com.quanxi.qxaimain.common.message.ymlConfig;
import com.quanxi.qxaimain.common.util.RestTemplateUtils.RestTemplateUtils;
import com.quanxi.qxaimain.common.util.sqlFormat.sqlFormat;
import com.quanxi.qxaimain.dao.forVue.DMLMapper;
import com.quanxi.qxaimain.dao.indicators.indicatorsDataMapper;
import com.quanxi.qxaimain.service.downloadExcelServer.downloadExcelServer;
import com.sargeraswang.util.ExcelUtil.ExcelLogs;
import com.sargeraswang.util.ExcelUtil.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;

import static java.lang.Thread.sleep;

/**
 * @Author lyx
 * @create 2023/2/17 15:37
 * vue接口
 */

@Slf4j
@RestController
@RequestMapping("/fileManageDetail")
@Api(tags = "文件管理")
public class fileManageDetailController {

    @Resource
    indicatorsDataMapper indicatorsDataMapper;

    @Resource
    private DMLMapper dmlMapper;
    @PostMapping("/search")
    public Object search(String id){
        String selectSql1="select sqlSelect from qx_t_file where  id='"+id+"'";
        List<LinkedHashMap<String, Object>> linkedHashMapList = dmlMapper.exec_sql1(selectSql1);
        String sqlSelect2 = linkedHashMapList.get(0).get("sqlSelect").toString();

        List<LinkedHashMap<String, Object>> mapList = dmlMapper.exec_sql4(sqlSelect2);
        return mapList;
    }

    @PostMapping("/searchInd_id")
    public Object searchInd_id(String id) throws InterruptedException {
        String selectSql=" select\n" +
                "sid,\n" +
                "pid,\n" +
                "kpi_type,\n" +
                "source,\n" +
                "dept_code,\n" +
                "dept_name,\n" +
                "kpi_code,\n" +
                "to_number(kpi_result) as kpi_result,\n" +

                "out_date_type,\n" +
                "out_date_year,\n" +
                "out_date_season,\n" +
                "out_date_month,\n" +
                "org_id,\n" +
                "is_invalid,\n" +
                "is_del,\n" +
                "create_time,\n" +
                "0 as updatePercentage ,\n" +
                "'' as updateStatus ,\n" +
                "update_time from qx_t_kpi_result  where dept_name ='全院' and kpi_code= '"+id+"' and  is_del=0 ";




        List<LinkedHashMap<String, Object>> mapList = dmlMapper.exec_sql4(selectSql);

        for (int i = 0; i <mapList.size() ; i++) {

            String[] out_date_months = mapList.get(i).get("OUT_DATE_MONTH").toString().split("/");
            //  System.out.println(params.get(i).get("OUT_DATE_MONTH"));
            String startDate= out_date_months[0]+"-01 00:00:00";
            String[] s = out_date_months[1].split("-");
            String endDate = getLastDayOfMonth(Integer.parseInt(s[0]), Integer.parseInt(s[1]));

            mapList.get(i).put("startDate",startDate);
            mapList.get(i).put("endDate",endDate);
        }


        return mapList;
    }

    @PostMapping("/searchDeptData")
    public Object searchDeptData(String id,String date) throws InterruptedException {
        String selectSql="select dept_name,to_number(kpi_result) as kpi_result ,update_time from  qx_t_kpi_result where dept_name<>'全院' and  kpi_code='"+id+"' and out_date_month='"+date+"' and is_del=0 ";

        List<LinkedHashMap<String, Object>> mapList = dmlMapper.exec_sql4(selectSql);

        return mapList;
    }


    @Resource
    private  downloadExcelServer downloadExcelServer;

    @ApiOperation(value = "导出excel",  notes = "")
    @RequestMapping(value = "/downloadExcel", method= RequestMethod.GET )
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",       value = "文件id", required = false, dataType = "String"),
            @ApiImplicitParam(name = "excelName",       value = "文件名称", required = false, dataType = "String"),

    })

    public Object downloadExcel(  String excelName,String id, HttpServletResponse response) throws Exception{

    //    System.out.println(id+"==========================");

        String selectSql1="select sqlSelect from qx_t_file where  id='"+id+"'";
        List<LinkedHashMap<String, Object>> linkedHashMapList = dmlMapper.exec_sql1(selectSql1);
        String sqlSelect2 = linkedHashMapList.get(0).get("sqlSelect").toString();
     //   System.out.println(sqlSelect2+"==========================");


        List<Map<String, Object>> mapList=  new ArrayList<>();

            downloadExcelServer.downloadExcelSDQuery(excelName,sqlSelect2,false,1000000);

            //     ResponseVo responseVo = new ResponseVo(SUCCESS.getCode(),SUCCESS.getMsg(),jsonObjectList);
            return null;
        }



    @ApiOperation(value = "上传/导入excel",  notes = "")
    @PostMapping("/upload")
    public Object upload(  MultipartFile[] file,String id,String editor) throws IOException {

        String selectSql1="select sqlInsert,sqlSelect,tablename ,upload_time ,editor from qx_t_file where  id='"+id+"'";
        List<LinkedHashMap<String, Object>> linkedHashMapList = dmlMapper.exec_sql1(selectSql1);
        String sqlSelect= linkedHashMapList.get(0).get("sqlSelect").toString();
        String tablename = linkedHashMapList.get(0).get("tablename").toString();
        Object upload_time = linkedHashMapList.get(0).get("upload_time");
        String sqlInsert = linkedHashMapList.get(0).get("sqlInsert").toString();
        String editor_bak= linkedHashMapList.get(0).get("editor").toString();


        MultipartFile multipartFile = file[0];
        byte[] bytes = multipartFile.getBytes();
        InputStream inputStream = new ByteArrayInputStream(bytes);

        ExcelLogs logs = new ExcelLogs();
        Collection<Map> importExcel = ExcelUtil.importExcel(Map.class, inputStream, "yyyy/MM/dd HH:mm:ss", logs, 0);


        List<Map<String,Object>>listmap = new ArrayList<>();

        for (Map m : importExcel) {
       //     System.out.println(m);
            listmap.add(m);
        }

        // 删除之前先备份
     List<Map<String, Object>> mapListBak = dmlMapper.exec_sql_listmap4(sqlSelect);

        try{
        dmlMapper.delete4("delete from  "+tablename);
        dmlMapper.insert4(listmap,sqlInsert);
        dmlMapper.update1("update qx_t_file set upload_time =  sysdate() where  id ="+id);
        dmlMapper.update1("update qx_t_file set editor =  '"+editor+"' where  id ="+id);
       }
        catch (Exception e){
           //异常还原
            log.info(tablename+"--异常还原--"+e.getMessage());
           dmlMapper.insert4(mapListBak,sqlInsert);
           dmlMapper.update4("update "+tablename+" set upload_time ="+upload_time);
           dmlMapper.update1("update qx_t_file set upload_time =  "+upload_time +"  where  id ="+id);
            dmlMapper.update1("update qx_t_file set editor =  '"+editor_bak +"'  where  id ="+id);
           log.info("异常还原success");
            return e.getMessage();
       }




        return importExcel;


    }
     @Resource
    private ymlConfig ymlCofig;

    @PostMapping("/updateKpi")
    public Object updateKpi( @RequestBody List<JSONObject> params) throws InterruptedException {

        if (params==null){
        return null;
         //   "PID" -> "3-c8-全院-4-2022-01/2022-11"
        }

        ArrayList<Object> requestBody = new ArrayList<>();
        List<String> pidList= new ArrayList<>();
        String KPI_CODE="";



        for (int i = 0; i <params.size() ; i++) {
            String[] out_date_months = params.get(i).get("OUT_DATE_MONTH").toString().split("/");
          //  System.out.println(params.get(i).get("OUT_DATE_MONTH"));
            String startDate= out_date_months[0]+"-01 00:00:00";
            String[] s = out_date_months[1].split("-");
            String endDate = getLastDayOfMonth(Integer.parseInt(s[0]), Integer.parseInt(s[1]));
            String kpi_code = params.get(i).get("KPI_CODE").toString();


            String updateId = params.get(i).get("DEPT_NAME").toString()+params.get(i).get("OUT_DATE_MONTH").toString()+params.get(i).get("KPI_CODE").toString();


            KPI_CODE=    params.get(i).get("KPI_CODE").toString();

            //拼接新建层参数
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("startDate",startDate);
            jsonObject.put("endDate",endDate);
            ArrayList<String> listid = new ArrayList();
            listid.add(kpi_code);
            jsonObject.put("kpiCodeList",listid);
            requestBody.add(jsonObject);

            pidList.add(updateId);
        }

        String url = ymlCofig.getRegainDataUrl()+"/api/v1/qxqcsdbapi/indicators/updateIndicatorResults";
        //更新状态
        Integer UPDATEPERCENTAGE=0;
        String UPDATESTATUS="更新失败，接口信息："+url;
        try {
        String responsestr = RestTemplateUtils.postss(url, requestBody);
            System.out.println(responsestr.toString());
        net.sf.json.JSONObject response = net.sf.json.JSONObject.fromObject(responsestr);
        if (   response.getInt("code")==0){
             UPDATEPERCENTAGE=50;
             UPDATESTATUS="全院总值更新成功；各科室值更新失败"+response.getString("message");
        }
            if (  response.getInt("code")==1){
                UPDATEPERCENTAGE=100;
                UPDATESTATUS="success";
            }
        }catch (Exception e){
            UPDATEPERCENTAGE=0;
            UPDATESTATUS="更新失败，接口信息："+url+e.getMessage();
        }

   // 返回 dept_name ='全院' and 该 kpi_code 所有数据
        String selectSql="select\n" +
                "dept_name||out_date_month||kpi_code as  updateId,\n"+
                "sid,\n" +
                "pid,\n" +
                "kpi_type,\n" +
                "source,\n" +
                "dept_code,\n" +
                "dept_name,\n" +
                "kpi_code,\n" +
                "to_number(kpi_result) as kpi_result,\n" +

                "out_date_type,\n" +
                "out_date_year,\n" +
                "out_date_season,\n" +
                "out_date_month,\n" +
                "org_id,\n" +
                "is_invalid,\n" +
                "is_del,\n" +
                "create_time,\n" +
                "0 as updatePercentage ,\n" +
                "'' as updateStatus ,\n" +
                "update_time from qx_t_kpi_result where dept_name ='全院' and kpi_code= '"+KPI_CODE+"'and   is_del=0 "  ;

        List<LinkedHashMap<String, Object>> mapList = dmlMapper.exec_sql4(selectSql);

        for (int i = 0; i <mapList.size() ; i++) {
           if (pidList.contains( mapList.get(i).get("UPDATEID").toString())){
               mapList.get(i).put("UPDATEPERCENTAGE",UPDATEPERCENTAGE);
          //     System.out.println("1000==="+mapList.get(i).get("PID").toString());
               mapList.get(i).put("UPDATESTATUS",UPDATESTATUS);

           };


        }

        return mapList;


    }


    public static String getLastDayOfMonth(int year, int month) {
        Calendar cal = Calendar.getInstance();

        if (year != 0) {
            cal.set(Calendar.YEAR, year);
        }
        cal.set(Calendar.MONTH, month);
        //设置当前前天为零，即上个月最后一天
        cal.set(Calendar.DATE, 0);
        Calendar returnCal = Calendar.getInstance();
        if (year != 0) {
            returnCal.set(Calendar.YEAR, year);
        }
        returnCal.set(Calendar.MONTH, month - 1);
        returnCal.set(Calendar.DATE, cal.get(Calendar.DATE));
        return DateFormatUtils.format(returnCal.getTime(), "yyyy-MM-dd") + " 23:59:59";
    }


    @PostMapping("/selectList")
    public Object selectList()   {
        JSONObject jsonObject = new JSONObject();
        List<Map<String, Object>>  list = dmlMapper.find_selectlist("qxzsk_t_indicator_sql");
        ArrayList<Map<String, Object>> selectlist = new ArrayList<>();
        List<LinkedHashMap<String, Object>> linkedHashMapList = dmlMapper.exec_sql4("select distinct   out_date_month  from  qx_t_kpi_result  where  out_date_month <>'0' and  out_date_month is not null and is_del=0  order by out_date_month desc");



        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> map =new HashMap<>();
            map.put( "ind_id",list.get(i).get("ind_id").toString());
            map.put( "ind_name",list.get(i).get("ind_name").toString());
            selectlist.add(map);
        }

        jsonObject.put("indList",selectlist);
        jsonObject.put("timeList",linkedHashMapList);

        return jsonObject;
    }



    @PostMapping("/updateStatus")
    public Object updateStatus(String ind_id,String status)   {

        if (status.equals("true")) {
            dmlMapper.update1("update qxzsk_t_indicator_sql set status = 'true'  where  ind_id ='" + ind_id+"'");
        }else {
            dmlMapper.update1("update qxzsk_t_indicator_sql set status = null  where  ind_id ='" + ind_id+"'");
        }

        return true;
    }

    @PostMapping("/deleteStatus")
    public Object deleteStatus(String ind_id)   {

        if (!ind_id.equals("")) {
            dmlMapper.update1("delete from qxzsk_t_indicator_sql where  ind_id ='" + ind_id + "'");
        }

        return true;
    }






}